package com.totoro.metrics;

import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;

import java.util.Random;

/**
 * Timer用来测量一段代码被调用的速率和用时。
 * Created by Niki on 2018/8/28 14:57
 */
public class TimerDemo {
    private static final MetricRegistry metrics = new MetricRegistry();

    private static Timer timer = metrics.timer(MetricRegistry.name(TimerDemo.class, "response"));
    private static Random random = new Random();

    private static void response() {
        Timer.Context context = timer.time();
        try {
            Thread.sleep(random.nextInt(800));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            context.stop();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        OutputUtil.console(metrics);

        int i = 0;
        while (i < 100) {
            response();
            Thread.sleep(500);
        }

        /*
        -- Timers ----------------------------------------------------------------------
com.totoro.metrics.TimerDemo.response
             count = 4
         mean rate = 1.31 calls/second
     1-minute rate = 0.00 calls/second
     5-minute rate = 0.00 calls/second
    15-minute rate = 0.00 calls/second
               min = 211.09 milliseconds
               max = 489.13 milliseconds
              mean = 341.96 milliseconds
            stddev = 136.84 milliseconds
            median = 333.80 milliseconds
              75% <= 473.52 milliseconds
              95% <= 489.13 milliseconds
              98% <= 489.13 milliseconds
              99% <= 489.13 milliseconds
            99.9% <= 489.13 milliseconds

         */
    }
}
